package com.hoas.api.server;

import com.hoas.api.core.intf.ApiService;
import com.hoas.api.core.entity.ApiResult;
import com.hoas.api.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@EnableAutoConfiguration
@ComponentScan
@Configuration
@ImportResource(locations = {"classpath:bean.xml"})
public class ApiStarter {
	
	@Autowired
	private ApiService apiService;
	
	@RequestMapping(value = "/api")
	@ResponseBody
    public ApiResult api(HttpServletRequest request) {
        try {
        	String businessId = request.getParameter("businessId");
        	String token = request.getParameter("token");
        	String paramStr = request.getParameter("param");
			return apiService.callApi(businessId, token, paramStr);
		} catch (BusinessException e) {
			ApiResult result = new ApiResult(e.getCode(), e.getMessage());
			return result;
		}
    }
    
	@RequestMapping(value = "/login")
    @ResponseBody
    public ApiResult login(HttpServletRequest request) {

		String username = request.getParameter("username");
    	String password = request.getParameter("password");
    	try {
			return apiService.getAccessToken(username, password);
		} catch (BusinessException e) {
			ApiResult result = new ApiResult(e.getCode(), e.getMessage());
			return result;
		}
    }
	
	@RequestMapping(value = "/refreshToken")
    @ResponseBody
    public ApiResult refreshToken(HttpServletRequest request) {
    	String refreshToken = request.getParameter("refreshToken");
    	try {
			return apiService.refreshAccessToken(refreshToken);
		} catch (BusinessException e) {
			ApiResult result = new ApiResult(e.getCode(), e.getMessage());
			return result;
		}
    }

	@RequestMapping(value = "/ping")
	@ResponseBody
	public String ping(HttpServletRequest request) {
		return "pong";
	}

    public static void main(String[] args) throws Exception {
    	
        SpringApplication.run(ApiStarter.class, args);
    }
    
}